package com.zhx.filter;

import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import java.io.File;
import java.io.IOException;

/**
 * @program: web-springboot
 * @author: zhx
 * @create: 2021-05-22 21:19
 **/
@Component //交给容器
@WebFilter(urlPatterns = "/*") //拦截路径，拦截所有请求
public class EncodingFilter implements Filter{
    @Override
    public void init(FilterConfig filterConfig) {
        System.out.println("初始化编码过滤");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        long start = System.currentTimeMillis();
        //执行过滤方法，每次拦截到的请求，都会执行这个方法
        //处理请求乱码
        servletRequest.setCharacterEncoding("utf-8");
        //处理响应乱码
        servletResponse.setContentType("text/html;charset=utf-8");
        //放行请求，放给下一个过滤器
        filterChain.doFilter(servletRequest, servletResponse);
        System.out.println("结束了编码过滤器，耗时："+(System.currentTimeMillis()-start));
    }

    @Override
    public void destroy() {
        System.out.println("销毁编码过滤");
    }
}
